package dice.sinanya.dice.game;

import com.forte.qqrobot.beans.messages.types.MsgGetTypes;
import dice.sinanya.entity.EntityTypeMessages;
import dice.sinanya.exceptions.NotMasterException;
import dice.sinanya.exceptions.ReplyRecursiveException;
import dice.sinanya.exceptions.ReplyTooShortException;
import dice.sinanya.tools.makedata.ModeForReply;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.DocumentException;

import java.util.ArrayList;
import java.util.Arrays;

import static dice.sinanya.system.MessagesTag.TAG_REPLY_GET;
import static dice.sinanya.system.MessagesTag.TAG_REPLY_SET;
import static dice.sinanya.tools.checkdata.CheckPower.*;
import static dice.sinanya.tools.makedata.Sender.sender;
import static dice.sinanya.tools.makedata.StringFormatById.stringFormatById;

public class Reply {
    private static final Logger logger = LogManager.getLogger(Reply.class.getName());
    private final EntityTypeMessages entityTypeMessages;
    private final ModeForReply modeForReply;

    public Reply(EntityTypeMessages entityTypeMessages) throws NotMasterException {
        this.entityTypeMessages = entityTypeMessages;
        modeForReply = new ModeForReply(entityTypeMessages);
    }

    public void set() throws ReplyTooShortException, ReplyRecursiveException, NotMasterException, DocumentException {
        if (!checkMasterAndSendByPrNotSendByGroup(entityTypeMessages)){
            return;
        }
        String tag = TAG_REPLY_SET;
        String msg = entityTypeMessages.getMsgGet().getMsg().trim().replaceFirst(tag.substring(0, tag.length() - 8), "").trim();
        ArrayList<String> msgList = new ArrayList<>(Arrays.asList(msg.split(" +")));
        String key = msgList.get(0);
        if (key.length() < 4 && !key.equals("自身")) {
            throw new ReplyTooShortException(entityTypeMessages);
        }
        msgList.remove(0);
        String values = StringUtils.join(msgList, " ");
        if (values.equals("")) {
            modeForReply.remove(msg);
            sender(entityTypeMessages, stringFormatById("回复词关键字%s已删除", msg));
        } else {
            modeForReply.insert(key, values);
            sender(entityTypeMessages, "回复词设置完毕");
        }
    }

    public void get() throws NotMasterException {
        if (!checkMasterAndSendByPrNotSendByGroup(entityTypeMessages)){
            return;
        }
        String tag = TAG_REPLY_GET;
        String msg = entityTypeMessages.getMsgGet().getMsg().trim().replaceFirst(tag.substring(0, tag.length() - 2), "").trim();
        sender(entityTypeMessages, modeForReply.get(msg));
    }

    public void list() throws NotMasterException {
        if (!checkMasterAndSendByPrNotSendByGroup(entityTypeMessages)){
            return;
        }
        sender(entityTypeMessages, modeForReply.list());
    }

}
